package com.hanlin.backend.service.impl;

import cn.hutool.core.util.StrUtil;
import com.hanlin.backend.common.entity.HlUser;
import com.hanlin.backend.common.error.CommonException;
import com.hanlin.backend.common.error.ErrorCodeEnum;
import com.hanlin.backend.common.service.HlServiceFactory;
import com.hanlin.backend.common.util.JwtUtil;
import com.hanlin.backend.common.util.MD5Utils;
import com.hanlin.backend.common.util.RedisUtil;
import com.hanlin.backend.common.util.ResultCommon;
import com.hanlin.backend.service.HlUserLoginLogService;
import com.hanlin.backend.service.HlUserService;
import com.hanlin.backend.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：登录
 *
 * @author:hl.yuan
 * @date:2020-12-27
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private HlUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HlUserLoginLogService hlUserLoginLogService;

    @Value("${system.jwtTimeOut}")
    private Long tokenTime;

    @Override
    public ResultCommon login(String username, String password, HttpServletRequest request) {
        ResultCommon result = new ResultCommon();
        HlUser hlUser = userService.findByUserName(username);
        if (hlUser == null) {
            result.setMessage("用户名或密码错误");
            result.setCode("1");
            hlUserLoginLogService.saveLoginLog(result.getCode(),hlUser,request);
            return result;
        }
        if (!hlUser.getPassword().equals(password)) {
            result.setMessage("用户名或密码错误");
            result.setCode("1");
            hlUserLoginLogService.saveLoginLog(result.getCode(),hlUser,request);
            return result;
        }
        // 生成 Token
        String token = JwtUtil.sign(username, password);
        // 把生成的token放入redis
        redisUtil.set("user_" + username, token, tokenTime);
        Map param = new HashMap();
        param.put("token", token);
        result.setData(param);
        // 存入登录记录
        hlUserLoginLogService.saveLoginLog(result.getCode(),hlUser,request);
        return result;
    }

    @Override
    public void updatePassWord(HlUser user, String passWord, String passWordNew1, String passWordNew2) throws CommonException {
        // 先判断token解析的用户是否为空
        if (user == null) {
            throw new CommonException(ErrorCodeEnum.SYS_ERROR, "token解析出来的用户为空！");
        }
        // 判断两次密码驶入是否一致。
        if (!StrUtil.equals(passWordNew1, passWordNew2)) {
            throw new CommonException(ErrorCodeEnum.SYS_ERROR, "两次输入密码不一致！");
        }
        // 加密输入的密码，和数据库存储的配对
        String encrypt = MD5Utils.encrypt(user.getUsername(), passWord);
        if (!StrUtil.equals(user.getPassword(), encrypt)) {
            // 当不相同后，抛出异常
            throw new CommonException(ErrorCodeEnum.SYS_ERROR, "旧密码输入不正确！");
        }
        // 加密新密码，存储数据库
        String encryptNew = MD5Utils.encrypt(user.getUsername(), passWordNew1);
        user.setPassword(encryptNew);
        userService.saveOrUpdate(user);
        // 修改密码后，应该需要把redis里的缓存给清理掉
    }

    @Override
    public String resetPassWord(Integer userId) {
        if (userId == null) {
            throw new CommonException(ErrorCodeEnum.SYS_ERROR, "userId为空！");
        }
        // 获取全局参数里配置的密码，如果没有，就默认是111
        String password = HlServiceFactory.getSettingService().getSetting("COMMON", "PASSWORD", "111");

        HlUser hlUser = userService.getById(userId);
        if (hlUser == null) {
            throw new CommonException(ErrorCodeEnum.SYS_ERROR, "userId错误！");
        }
        // 加密
        String encrypt = MD5Utils.encrypt(hlUser.getUsername(), password);
        // 设置密码
        hlUser.setPassword(encrypt);
        // 保存
        userService.saveOrUpdate(hlUser);

        return password;
    }
}
